package com.minggo.charmword.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.minggo.charmword.R;
import com.minggo.charmword.bitmap.FinalBitmap;
import com.minggo.charmword.bitmap.FinalBitmap.LoadFinishListener;
import com.minggo.charmword.logic.AroundWordUtil;
import com.minggo.charmword.model.Around;
import com.minggo.charmword.service.CharmWordApplication;

/**
 * 周围的人页面 整个屏幕上下差对应的纬度是[0.015°]，经度是[0.01]
 * 
 * @author minggo
 * @date 2014-9-28 下午1:14:42
 */
public class AroundMapActivity extends Activity implements OnMarkerClickListener, LoadFinishListener {

	private MapView mapView;
	private LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationMode mCurrentMode;
	private BaiduMap mBaiduMap;
	boolean isFirstLoc = true;// 是否首次定位
	private View aroundV;
	private AroundWordUtil aroundWordUtil;
	private List<Around> aroundList = new ArrayList<Around>();
	private List<ImageView> imageViewList = new ArrayList<ImageView>();
	private Map<Integer, BitmapDescriptor> descriptorList = new HashMap<Integer, BitmapDescriptor>();
	private FinalBitmap finalBitmap;
	private BDLocation currentbdLocation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_around_word);
		initUI();
		initData();

		finalBitmap = FinalBitmap.create(this);
		// finalBitmap.configLoadfailImage(R.drawable.map_mark_bg);
		// finalBitmap.configLoadingImage(R.drawable.map_mark_bg);
		CharmWordApplication.allActivities.add(this);
	}

	private void initUI() {

		mapView = (MapView) findViewById(R.id.bmapView);
		aroundV = findViewById(R.id.lo_around_back);
		aroundV.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				onBackPressed();
			}
		});
	}

	private void initData() {

		mCurrentMode = LocationMode.NORMAL;
		mBaiduMap = mapView.getMap();

		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
		// 定位初始化
		mLocClient = new LocationClient(this.getApplicationContext());
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		// option.setCoorType("gcj02"); // 设置坐标类型
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(30000);
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
		option.setIsNeedAddress(true);
		// option.setNeedDeviceDirect(true);

		// 116.4 39.9[北京]
		MapStatus status = new MapStatus.Builder().target(new LatLng(23.117055306224895, 113.2759952545166)).zoom(6)
				.build();
		mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(status));
		mLocClient.setLocOption(option);
		mLocClient.start();

		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, null));
		mBaiduMap.setOnMarkerClickListener(this);
		/**
		 * 地图状态改变的监听器[用来监听手势滑动后的的中心经纬度变化]
		 */
		mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {

			@Override
			public void onMapStatusChangeStart(MapStatus mapStatus) {
			}

			@Override
			public void onMapStatusChangeFinish(MapStatus mapStatus) {
				System.out.println("---longitude-->" + mapStatus.target.longitude + ",latitude-->"
						+ mapStatus.target.latitude);

				if ((Math.abs(currentbdLocation.getLatitude() - mapStatus.target.latitude) > 0.005)
						|| (Math.abs(currentbdLocation.getLongitude() - mapStatus.target.longitude) > 0.003)) {

					BDLocation location = new BDLocation();
					currentbdLocation = location;
					location.setLatitude(mapStatus.target.latitude);
					location.setLongitude(mapStatus.target.longitude);
					requestAround(location);
				}
			}

			@Override
			public void onMapStatusChange(MapStatus mapStatus) {
			}
		});
		if (CharmWordApplication.getInstance().mbdLocation != null) {
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(CharmWordApplication.getInstance().mbdLocation.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(0).latitude(CharmWordApplication.getInstance().mbdLocation.getLatitude())
					.longitude(CharmWordApplication.getInstance().mbdLocation.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);

			currentbdLocation = CharmWordApplication.getInstance().mbdLocation;
			MapStatus status1 = new MapStatus.Builder()
					.target(new LatLng(CharmWordApplication.getInstance().mbdLocation.getLatitude(),
							CharmWordApplication.getInstance().mbdLocation.getLongitude())).zoom(17).build();
			mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(status1));

		}
	}

	/**
	 * 请求周围数据
	 */
	private void requestAround(BDLocation location) {
		double longitude = location.getLongitude();
		double latitude = location.getLatitude();

		// System.out.println("定位到到的经纬度--->" + longitude + "," + latitude
		// +","+location.getProvince()+ "," +
		// location.getCity()+","+location.getDistrict()+","+location.getStreet()+","+location.getStreetNumber());
		List<Around> aroundList = new ArrayList<Around>();
		Random random = new Random();
		for (int i = 0; i < 10; i++) {

			Around around = new Around();
			int randLat = random.nextInt(8)-1;
			int randLon = random.nextInt(6)-1;

			if (randLat % 2 == 0) {
				around.latitude = latitude + (randLat * 0.001);
			} else {
				around.latitude = latitude - (randLat * 0.001);
			}
			if (randLon % 2 == 0) {
				around.longitude = longitude + (randLon * 0.001);
			} else {
				around.longitude = longitude - (randLon * 0.001);
			}

			around.userAvatar = "http://b.img.youboy.com/201010/12/g3_6576976.jpg";
			aroundList.add(around);
		}

		handler.obtainMessage(AroundWordUtil.GET_AROUND, aroundList).sendToTarget();

		/*
		 * aroundWordUtil = new AroundWordUtil(longitude, altitude, handler);
		 * aroundWordUtil.execute();
		 */
	}

	/**
	 * 刷新标柱
	 */
	private void refreshMark(List<Around> aroundsList) {
		if (aroundList.isEmpty()) {
			aroundList.addAll(aroundsList);
		} else {
			aroundList.clear();
			imageViewList.clear();
			descriptorList.clear();
			aroundList.addAll(aroundsList);
			mBaiduMap.clear();
			int i = 0;
			for (Around around : aroundList) {
				ImageView imageView = new ImageView(this);
				imageView.setTag(i);
				imageView.setLayoutParams(new LayoutParams(this.getResources().getDimensionPixelSize(
						R.dimen.map_market_size), this.getResources().getDimensionPixelSize(R.dimen.map_market_size)));
				imageView.setBackgroundResource(R.drawable.map_mark_bg);
				int padding1 = this.getResources().getDimensionPixelSize(R.dimen.map_market_padding);
				int padding_bottom = this.getResources().getDimensionPixelSize(R.dimen.map_market_padding_bottom);
				imageView.setPadding(padding1, padding1, padding1, padding_bottom);
				imageView.setScaleType(ScaleType.FIT_CENTER);

				imageViewList.add(imageView);
				// finalBitmap.configBitmapMaxHeight(this.getResources().getDimensionPixelSize(R.dimen.map_market_size));
				// finalBitmap.configBitmapMaxWidth(this.getResources().getDimensionPixelSize(R.dimen.map_market_size));

				finalBitmap.display(imageView, around.userAvatar, this);
				descriptorList.put(i, BitmapDescriptorFactory.fromView(imageView));
				LatLng latLng = new LatLng(around.latitude, around.longitude);
				OverlayOptions ooA = new MarkerOptions().position(latLng)
						.icon(descriptorList.get(descriptorList.size() - 1)).zIndex(9).draggable(true);
				Marker marker = (Marker) (mBaiduMap.addOverlay(ooA));
				marker.setZIndex(i);
				++i;
			}
		}

	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {

			System.out.println("定位回来了");

			// map view 销毁后不在处理新接收的位置
			if (location == null || mapView == null) {
				System.out.println("没有定位成功");
				return;
			}

			requestAround(location);
			MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
			// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(0).latitude(location.getLatitude()).longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				currentbdLocation = location;
				MapStatus status = new MapStatus.Builder()
						.target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(17).build();
				mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(status));

			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
			System.out.println("定位回来了");
		}

	}

	private Handler handler = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case AroundWordUtil.GET_AROUND:
				if (msg.obj != null) {
					refreshMark((List<Around>) msg.obj);
				}
				break;

			default:
				break;
			}
			return false;
		}
	});

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		mLocClient.stop();
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		mapView.onResume();
		super.onResume();
		mLocClient.registerLocationListener(myListener);
	}

	@Override
	protected void onPause() {
		mapView.onPause();
		mLocClient.unRegisterLocationListener(myListener);
		super.onPause();

	}

	@Override
	public boolean onMarkerClick(Marker market) {
		System.out.println("第几个标记--->" + market.getZIndex());
		return false;
	}

	private void refreshLoadImage() {

		/*
		 * for (int i = 0; i < descriptorList.size(); i++) {
		 * descriptorList.get(i).recycle(); } descriptorList.clear();
		 */

		if (!imageViewList.isEmpty()) {
			mBaiduMap.clear();
			for (int i = 0; i < imageViewList.size(); i++) {
				if (descriptorList.containsKey(i)) {
					descriptorList.remove(i);
					descriptorList.put(i, BitmapDescriptorFactory.fromView(imageViewList.get(i)));
				}
				LatLng latLng = new LatLng(aroundList.get(i).latitude, aroundList.get(i).longitude);
				OverlayOptions ooA = new MarkerOptions().position(latLng)
						.icon(descriptorList.get(descriptorList.size() - 1)).zIndex(9).draggable(true);
				Marker marker = (Marker) (mBaiduMap.addOverlay(ooA));
				marker.setZIndex(i);
			}
		}
	}

	@Override
	public void loadFinish(ImageView imageView) {
		for (int i = 0; i < imageViewList.size(); i++) {
			if (imageViewList.get(i).getTag() == imageView.getTag()) {
				imageView.setBackgroundResource(R.drawable.map_mark_bg);
				imageView.setLayoutParams(new LayoutParams(this.getResources().getDimensionPixelSize(
						R.dimen.map_market_size), this.getResources().getDimensionPixelSize(R.dimen.map_market_size)));

				int padding1 = this.getResources().getDimensionPixelSize(R.dimen.map_market_padding);
				int padding_bottom = this.getResources().getDimensionPixelSize(R.dimen.map_market_padding_bottom);
				imageView.setPadding(padding1, padding1, padding1, padding_bottom);
				// imageView.setScaleType(ScaleType.FIT_CENTER);
				imageViewList.remove(i);
				imageViewList.add(imageView);

			}
		}
		refreshLoadImage();

	}

}
